<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}账期配置`"
    width="760"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div v-loading="loading">
      <el-form
        ref="formRef"
        :model="formValues"
        :rules="rules"
        label-position="top"
        label-width="120px"
      >
        <el-form-item label="账期名称" prop="bp_name">
          <el-input v-model="formValues.bp_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="配置">
          <div class="flex items-center justify-center">
            <div class="w-[150px]">
              <el-select
                v-model="formValues.bp_type"
                placeholder="请选择条件"
                @change="resetFormData"
                class="w-full"
              >
                <el-option
                  v-for="condition in option['logistics_bp_type']"
                  :key="condition.value"
                  :label="condition.label"
                  :value="condition.value"
                >
                </el-option>
              </el-select>
            </div>
            <div
              v-for="field in currentFormFields"
              :key="field.name"
              :class="field.class"
            >
              <el-input
                v-if="field.type === 'input'"
                v-model="formData[field.name]"
                :placeholder="field.placeholder"
              ></el-input>
              <el-select
                v-else-if="field.type === 'select'"
                v-model="formData[field.name]"
                :placeholder="field.placeholder"
                class="w-full"
              >
                <el-option
                  v-for="option in field.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="账期生效日期" prop="time">
          <el-date-picker
            v-model="formValues.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 2, 1, 23, 59, 59),
            ]"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            inline-prompt
            v-model="formValues.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formValues.remark" type="textarea" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { formFieldsConfig } from "./data.js";
import { getTenDateRange } from "@/utils/time.js";
import { bpConfigDetail, bpConfigCreate, bpConfigUpdate } from "../../api.js";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  option: { type: Object, default: () => ({}) },
});
const rules = reactive({
  bp_name: [{ required: true, message: "请输入账期名称", trigger: "blur" }],
  time: [{ required: true, message: "请选择时间", trigger: "change" }],
});
const { option } = toRefs(props);
// //配置
const formFieldsConfigData = computed(() => {
  let formConfig = JSON.parse(JSON.stringify(formFieldsConfig));
  let obj = { ...formConfig };
  for (let key in obj) {
    if (Array.isArray(obj[key])) {
      obj[key]?.forEach((field) => {
        if (field.type === "select") {
          field.options = option.value?.[field.options] || [];
        }
      });
    }
  }
  const { settle_type } = formData.value;
  const { bp_type } = formValues.value;
  if (settle_type && (bp_type === 3 || bp_type === 4)) {
    const key = bp_type;
    if (Array.isArray(obj[key])) {
      obj[key].push({
        type: settle_type !== 10 ? "input" : "select",
        name: "settle_cycle",
        placeholder: "天数",
        options:
          settle_type == 10
            ? bp_type == 3
              ? option.value?.optMonth
              : option.value?.optLimit
            : undefined,
        class: "w-[150px]",
      });
    }
  }
  return obj;
});
const formData = ref({});
const currentFormFields = computed(
  () => formFieldsConfigData.value[formValues.value.bp_type] || []
);
const resetFormData = () => {
  formData.value = {};
  currentFormFields.value.forEach((field) => {
    formData.value[field.name] = field.type === "input" ? "" : null;
  });
};

const loading = ref(false);

const isEdit = computed(() => {
  return !!props.id;
});
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);
const getDetail = async (val) => {
  const { data } = await bpConfigDetail({ id: val });
  const { start_time, end_time } = data;
  for (let key in formValues.value) {
    formValues.value[key] = data[key];
  }
  if (start_time) {
    formValues.value.time = [start_time, end_time];
  }
  resetFormData();
  for (let k in formData.value) {
    formData.value[k] = data[k];
  }
  formData.value.settle_cycle = data?.settle_cycle || undefined;
};
const formValues = ref({
  id: null,
  status: 1,
  bp_name: null,
  bp_type: null,
  settle_type: null,
  settle_cycle: null,
  bp_time_type: null,
  time: getTenDateRange(),
  remark: null,
});
const formRef = ref();
const handleSave = async () => {
  try {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const { time } = formValues.value;
        let obj = {
          ...formValues.value,
          start_time: time[0],
          end_time: time[1],
          time: undefined,
        };
        let data = Object.assign({}, obj, formData.value);
        const { code, message } = await (isEdit.value
          ? bpConfigUpdate
          : bpConfigCreate)({
          ...data,
        });
        if (code != 200) return ElMessage.error(message);
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } else {
        return false;
      }
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  formValues.value = {
    id: null,
    status: 1,
    bp_name: null,
    bp_type: null,
    settle_type: null,
    settle_cycle: null,
    time: getTenDateRange(),
    remark: null,
  };
  formData.value = {};
  formRef.value?.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style></style>
